//
//  MovieViewController.m
//  JWMovie
//
//  Created by Jorn.Wu on 15/7/17.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "MovieViewController.h"
#import "JWMovieCellModel.h"
#import "JWMovieCell.h"
#import "constant.h"
#import "JWPosterMovieCell.h"
#import "JWPosterTopMovieCell.h"

@interface MovieViewController ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) NSArray *moviesAr;
@property (nonatomic, assign) BOOL isOne;//是否为第一页
@property (nonatomic, strong) UIView *posterView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIScrollView *posterScrollVeiw;
@property (nonatomic, strong) UIView *posterTopView;
@property (nonatomic, assign) BOOL isDown;//是否处于下拉状态
@property (nonatomic, strong) UIButton *posterTopBtn;
@property (nonatomic, strong) UIScrollView *topScrollView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UIButton *coverBtn;
@property (nonatomic, strong) NSDictionary *jsonDic;


@end

@implementation MovieViewController

CGFloat pading = 20;//间距

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"北美榜";
        self.navigationController.navigationBar.translucent = NO;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isOne = YES;
    _isDown = NO;
    self.jsonDic = [self webRequestWithURLName:@"http://api.douban.com/v2/movie/us_box"];
    
    [self loadTableView];
    [self reloadNavigation];
    [self loadPosterView];
    [self addScrollView];
    [self addTitleLabel];
    [self addPosterMovieCells];
    [self addTopView];
    [self addTopScrollView];
    [self addTopMovieCells];
    [self addLights];
    [self addGesture];
    [self addCoverBtn];
}

#pragma mark - 导航栏的加载和设置

- (void)reloadNavigation{
    self.navigationController.navigationBar.translucent = NO;
    
    UIView *ItemView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 50, 30)];
    
    UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn1 setImage:[UIImage imageNamed:@"list_home"] forState:UIControlStateNormal];
    btn1.tag = 1;
    [btn1 sizeToFit];
    [btn1 addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    btn1.hidden = NO;
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:[UIImage imageNamed:@"poster_home"] forState:UIControlStateNormal];
    btn2.tag = 2;
    [btn2 sizeToFit];
    [btn2 addTarget:self action:@selector(rightBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    btn2.hidden = YES;
    
    [ItemView addSubview:btn1];
    [ItemView addSubview:btn2];
    
    UIBarButtonItem *Item = [[UIBarButtonItem alloc] initWithCustomView:ItemView];
    self.navigationItem.rightBarButtonItem = Item;
    
}

# pragma mark - 页面的翻转和海报界面还原

- (void)rightBtnAction:(UIButton *)btn{
    
    UIView *BtnView = self.navigationItem.rightBarButtonItem.customView;
    UIButton *btn1 = (UIButton *)[BtnView viewWithTag:1];
    UIButton *btn2 = (UIButton *)[BtnView viewWithTag:2];
    
    if (_isOne) {
        [UIView transitionWithView:BtnView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromLeft animations:nil completion:nil];
    }else {
        [UIView transitionWithView:BtnView duration:0.5 options:UIViewAnimationOptionTransitionFlipFromRight animations:nil completion:nil];
        
    }

    [self fliPViewWithView:self.posterView andView:self.tableView isOne:_isOne];
    
    btn1.hidden = !btn1.hidden;
    btn2.hidden = !btn2.hidden;
    
    
    
    
    
    if (_isOne) {//(只在海报页面有效)
        UIScrollView *scrollView = (UIScrollView *)[self.posterView viewWithTag:1];
        
        for (JWPosterMovieCell *obj in scrollView.subviews) {
            obj.isFirst = NO;//页面自动还原,假设所有的页面都翻转过了,强制翻转为正面
            if (_isDown) {
                [self posterTopBtnAction:self.posterTopBtn];//让下拉收回
            }
        }
    }
    
}

#pragma mark - 翻页设置

- (void)fliPViewWithView:(UIView *)view1 andView:(UIView *)view2 isOne:(BOOL)isOne{
    UIViewAnimationOptions option = _isOne?UIViewAnimationOptionTransitionFlipFromLeft:UIViewAnimationOptionTransitionFlipFromRight;
    if (isOne) {
        [UIView transitionFromView:view1 toView:view2 duration:0.5 options:option completion:nil];
    }else {
        [UIView transitionFromView:view2 toView:view1 duration:0.5 options:option completion:nil];
    }
    _isOne = !_isOne;
}

//----------------------------------列表---------------------------------------------------------------

#pragma mark - 电影数组和文件的解析


- (NSArray *)moviesAr{

    NSArray *listAr = [self.jsonDic objectForKey:@"subjects"];
    
    if (!_moviesAr) {
        
        NSMutableArray *tempAr = [NSMutableArray array];
        for (int i = 0; i < listAr.count; i++) {
            NSDictionary *movieInfoDic = [listAr objectAtIndex:i];
            NSDictionary *subjectDic = [movieInfoDic objectForKey:@"subject"];
            JWMovieCellModel *movieModel = [[JWMovieCellModel alloc] initWithDictionary:subjectDic];
            [tempAr addObject:movieModel];
        }
        _moviesAr = tempAr;
        
    }
    return _moviesAr;
}

#pragma mark - 列表页面

- (void)loadTableView{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, JWScreenWidth, JWScreenHeight - 64) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_main@2x"]];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    
    [self.view addSubview:_tableView];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.moviesAr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JWMovieCell *cell = [JWMovieCell tableViewCellWithTableView:tableView];
   JWMovieCellModel *model = self.moviesAr[indexPath.row];
    cell.movieModel = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}

//----------------------------------海报---------------------------------------------------------------

#pragma mark - 海报页面

- (void)loadPosterView{
    
    _posterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, JWScreenWidth, JWScreenHeight - 64)];
    _posterView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_main@2x"]];
    
    [self.view addSubview:_posterView];

}

- (void)addScrollView{
    
    _posterScrollVeiw = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 35, JWScreenWidth, 450)];
    _posterScrollVeiw.contentSize = CGSizeMake((240 + pading) * self.moviesAr.count + pading, 0);
    _posterScrollVeiw.contentOffset = CGPointMake(0, 0);
    _posterScrollVeiw.showsVerticalScrollIndicator = NO;
    _posterScrollVeiw.showsHorizontalScrollIndicator = NO;
    _posterScrollVeiw.tag = 1;
    _posterScrollVeiw.delegate = self;
    _posterScrollVeiw.backgroundColor = [UIColor yellowColor];
    
    [_posterView addSubview:_posterScrollVeiw];
    
}

- (void)addPosterMovieCells{
    
    for (int i = 0; i < self.moviesAr.count; i++) {
        JWPosterMovieCell *posterCell = [[JWPosterMovieCell alloc] initWithFrame:CGRectMake((240 + pading) * i + pading, (_posterScrollVeiw.frame.size.height - 410) / 2, 240, 410)];
        JWMovieCellModel *model = self.moviesAr[i];
        posterCell.movieModel = model;
        
        [self.posterScrollVeiw addSubview:posterCell];
        
    }
    
}

#pragma mark - 添加顶部视图

- (void)addTopView{
    _posterTopView = [[UIView alloc] initWithFrame:CGRectMake(0, -170, JWScreenWidth, 200)];
    UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:_posterTopView.bounds];
    bgImageView.image = [self resizeWithImageName:@"indexBG_home@2x"];
    _posterTopBtn = [[UIButton alloc] initWithFrame:CGRectMake((JWScreenWidth - 30) * 0.5, _posterTopView.frame.size.height - 30, 30, 30)];
    [_posterTopBtn addTarget:self action:@selector(posterTopBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_posterTopBtn setImage:[UIImage imageNamed:@"down_home@2x"] forState:UIControlStateNormal];
    
    [_posterTopView addSubview:bgImageView];
    [_posterTopView addSubview:_posterTopBtn];
    [self.posterView addSubview:_posterTopView];
    
}

#pragma mark - 拉伸图片

- (UIImage *)resizeWithImageName:(NSString *)name{
    UIImage *normal = [UIImage imageNamed:name];
    
    CGFloat top = normal.size.height * 0.05f; // 顶端盖高度
    CGFloat bottom = normal.size.height * 0.85f ; // 底端盖高度
    CGFloat left = normal.size.width * 0.0f; // 左端盖宽度
    CGFloat right = normal.size.width * 0.0f; // 右端盖宽度
    UIEdgeInsets insets = UIEdgeInsetsMake(top, left, bottom, right);
    // 指定为拉伸模式，伸缩后重新赋值
    UIImage *newImage = [normal resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch];
    
    return newImage;
    
}

#pragma mark - 下拉按钮的响应方法

- (void)posterTopBtnAction:(UIButton *)btn{
    _isDown = !_isDown;
    
    if (_isDown) {
        [UIView beginAnimations:nil context:nil];
        [UIView animateWithDuration:2.f animations:^{
            self.posterTopView.transform = CGAffineTransformMakeTranslation(0, 170);
            btn.imageView.transform = CGAffineTransformMakeRotation(M_PI);
            self.coverBtn.hidden = NO;
        }];
        [UIView commitAnimations];
    }else {
        [UIView beginAnimations:nil context:nil];
        [UIView animateWithDuration:2.f animations:^{
            self.posterTopView.transform = CGAffineTransformMakeTranslation(0, 0);
            btn.imageView.transform = CGAffineTransformMakeRotation(0);
            self.coverBtn.hidden = YES;
        }];
        [UIView commitAnimations];
    }
    
}

#pragma mark - 添加下拉轻扫手势

- (void)addGesture{
    UISwipeGestureRecognizer *swipeDown = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeDownAction)];
    swipeDown.direction = UISwipeGestureRecognizerDirectionDown;
    [self.view addGestureRecognizer:swipeDown];
}
- (void)swipeDownAction{
    [self posterTopBtnAction:self.posterTopBtn];
}

#pragma mark - 添加蒙版按钮

- (void)addCoverBtn{
    
    _coverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, JWScreenWidth, JWScreenHeight)];
    _coverBtn.backgroundColor = [UIColor blackColor];
    _coverBtn.alpha = 0.7;
    _coverBtn.hidden = YES;
    
    [_coverBtn addTarget:self action:@selector(coverBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.posterView insertSubview:_coverBtn belowSubview:self.posterTopView];
    
}

- (void)coverBtnAction{
    if (self.isDown) {
        [self posterTopBtnAction:self.posterTopBtn];
    }
}

#pragma mark - 添加顶部的scrollview

- (void)addTopScrollView{
    _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 15, JWScreenWidth, 150)];
    _topScrollView.contentSize = CGSizeMake((90 + 10) * self.moviesAr.count + 10, 0);
    _topScrollView.backgroundColor = [UIColor yellowColor];
    
    [self.posterTopView addSubview:_topScrollView];
    
}

- (void)addTopMovieCells{
    
    for (int i = 0; i < self.moviesAr.count; i++) {
        JWPosterTopMovieCell *posterTopCell = [[JWPosterTopMovieCell alloc] initWithFrame:CGRectMake((90 + 10) * i + 10, (_topScrollView.frame.size.height - 130) / 2, 90, 130)];
        posterTopCell.imageBtn.tag = i;
        [posterTopCell.imageBtn addTarget:self action:@selector(imageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        JWMovieCellModel *model = self.moviesAr[i];
        posterTopCell.movieModel = model;
        
        [self.topScrollView addSubview:posterTopCell];
        
    }
   
}

#pragma mark - 添加顶部的点击响应方法

- (void)imageBtnAction:(UIButton *)btn{
    
    if (btn.tag == 0) {
        self.posterScrollVeiw.contentOffset = CGPointMake(0, 0);
    }else if (btn.tag == self.moviesAr.count - 1) {
        self.posterScrollVeiw.contentOffset = CGPointMake(self.posterScrollVeiw.contentSize.width - JWScreenWidth, 0);
    }else {
        self.posterScrollVeiw.contentOffset = CGPointMake((240 + pading) * btn.tag + pading - (JWScreenWidth - 240) * 0.5, 0);
//        居中显示
    }
  
}

#pragma mark - 添加和设置titlelabel

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    CGFloat offset = self.posterScrollVeiw.contentOffset.x;
    int index = offset / (240 + pading) + 0.5;
    JWMovieCellModel *model = self.moviesAr[index];
    self.titleLabel.text = model.title;
  
}
- (void)addTitleLabel{
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 500, JWScreenWidth, 40)];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont systemFontOfSize:20];
    _titleLabel.backgroundColor = [UIColor yellowColor];

    [self.posterView addSubview:_titleLabel];
}

#pragma mark - 添加灯泡

- (void)addLights{
    UIImageView *leftLight = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, JWScreenWidth / 2, self.posterTopView.frame.size.height)];
    UIImageView *rightLight = [[UIImageView alloc] initWithFrame:CGRectMake(JWScreenWidth / 2, 0, JWScreenWidth / 2, self.posterTopView.frame.size.height)];
    
    leftLight.image = [UIImage imageNamed:@"light@2x"];
    rightLight.image = [UIImage imageNamed:@"light@2x"];
    
    [self.posterTopView addSubview:leftLight];
    [self.posterTopView addSubview:rightLight];

}

//-------------------------------------------------------------------------------------------------


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
